package com.nsgf.library.ui.page.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.kunminx.binding_recyclerview.adapter.BaseDataBindingAdapter;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.bean.WorkApprovalInfoBean;
import com.nsgf.library.data.bean.WorkOrderBean;
import com.nsgf.library.databinding.FragmentNagfManagerListBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.event.EventMsg;
import com.nsgf.library.ui.adapter.ManagerListAdapter;
import com.nsgf.library.ui.page.AlarmEventCompletedActivity;
import com.nsgf.library.ui.page.AlarmEventProcessActivity;
import com.nsgf.library.ui.page.BaseFragment;
import com.nsgf.library.ui.page.PatrolObjectSelectionActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.widget.prckerview.TimePickerView;
import com.nsgf.skjz.utils.ToastUtils;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class ManagerPageFragment extends BaseFragment {
    MessageFragmentStates mStates;

    private ManagerListAdapter mAdapter;

    private AccountRequester mAccountRequester;

    public static ManagerPageFragment newInstance(int type) {
        ManagerPageFragment messageFragment = new ManagerPageFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        messageFragment.setArguments(bundle);
        return messageFragment;
    }

    private int getType() {
        return getArguments().getInt("type");
    }

    @Override
    protected void initViewModel() {

        mStates = getFragmentScopeViewModel(MessageFragmentStates.class);
        mAccountRequester = getFragmentScopeViewModel(AccountRequester.class);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventMsg event) {
        if ("warning".equals(event.getMsg()))
            mBinding.smartRefreshLayout.autoRefresh();
    }

    private FragmentNagfManagerListBinding mBinding;

    @Override
    protected DataBindingConfig getDataBindingConfig() {

        mAdapter = new ManagerListAdapter(getContext());

        return new DataBindingConfig(R.layout.fragment_nagf_manager_list, BR.vm, mStates)
                .addBindingParam(BR.adapter, mAdapter)
                .addBindingParam(BR.click, new ClickProxy());
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        getLifecycle().addObserver(mAccountRequester);
        mBinding = (FragmentNagfManagerListBinding) getBinding();
        EventBus.getDefault().register(this);
        mBinding.smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                number++;
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                number = 1;
                getDatas(startTime, endTime);

            }
        });

        // 观察审批信息接口返回结果
        observeWorkApprovalInfoResult();

        mBinding.smartRefreshLayout.autoRefresh();

        if (0 == getType()) {
            mBinding.tvNsgfManagerD.setVisibility(View.VISIBLE);
            mBinding.tvNsgfManagerY.setVisibility(View.GONE);
        } else {
            mBinding.tvNsgfManagerY.setVisibility(View.VISIBLE);
            mBinding.tvNsgfManagerD.setVisibility(View.GONE);
        }
        mAdapter.setOnItemClickListener(new BaseDataBindingAdapter.OnItemClickListener<WorkOrderBean>() {
            @Override
            public void onItemClick(int viewId, WorkOrderBean item, int position) {

                if ("patrol.task".equals(item.getBusinessType())) {

                    startActivity(new Intent(getActivity(), PatrolObjectSelectionActivity.class)
                            .putExtra("id", item.getBusinessCode()));
                } else {

                    if (1 == item.getStatus()) {
                        startActivity(new Intent()
                                .putExtra("id", item.getBusinessCode())
                                .setClass(getActivity(), AlarmEventCompletedActivity.class));
                    } else {
                        startActivity(new Intent()
                                .putExtra("id", item.getBusinessCode())
                                .setClass(getActivity(), AlarmEventProcessActivity.class));

                    }
                }
            }
        });

    }

    private String search = "";

    public void search(String search) {
        this.search = search;
        mBinding.smartRefreshLayout.autoRefresh();
    }

    public void onRefresh() {
        mBinding.smartRefreshLayout.autoRefresh();
    }

    private int number = 1;

    /**
     * 观察审批信息接口返回结果
     */
    private void observeWorkApprovalInfoResult() {
        mAccountRequester.getWorkApprovalInfoResult().observe(this, dataResult -> {
            if (dataResult != null && dataResult.getResponseCode() == 200) {
                WorkApprovalInfoBean workApprovalInfoBean = dataResult.getData();

                if (workApprovalInfoBean != null && workApprovalInfoBean.getRecords() != null) {
                    // 获取 records 列表
                    List<WorkApprovalInfoBean.RecordBean> records = workApprovalInfoBean.getRecords();

                    // 将 records 转换为 WorkOrderBean 列表
                    List<WorkOrderBean> workOrderList = convertToWorkOrderList(records);

                    // 更新适配器
                    mAdapter.submitList(workOrderList);

                    // 更新 UI
                    if (records.size() > 0) {
                        mBinding.notdata.setVisibility(View.GONE);
                    } else {
                        mBinding.notdata.setVisibility(View.VISIBLE);
                    }

                    // 如果是待办类型，发送 badge 消息
                    if (0 == getType()) {
                        EventMsg eventMsg = new EventMsg();
                        eventMsg.setMsg("badge");
                        eventMsg.setContent(String.valueOf(records.size()));
                        EventBus.getDefault().post(eventMsg);
                    }
                } else {
                    mAdapter.submitList(new ArrayList<>());
                    mBinding.notdata.setVisibility(View.VISIBLE);
                }
            } else {
                mAdapter.submitList(new ArrayList<>());
                mBinding.notdata.setVisibility(View.VISIBLE);
            }

            // 结束刷新
            if (mBinding != null && mBinding.smartRefreshLayout != null) {
                mBinding.smartRefreshLayout.finishRefresh();
            }
        });
    }

    /**
     * 将 WorkApprovalInfoBean.RecordBean 列表转换为 WorkOrderBean 列表
     */
    private List<WorkOrderBean> convertToWorkOrderList(List<WorkApprovalInfoBean.RecordBean> records) {
        List<WorkOrderBean> workOrderList = new ArrayList<>();
        for (WorkApprovalInfoBean.RecordBean record : records) {
            WorkOrderBean workOrder = new WorkOrderBean();
            // 映射字段
            workOrder.setOrderCode(record.getBusinessCode()); // businessCode 映射到 orderCode
            workOrder.setTaskName(record.getApprovalName()); // approvalName 映射到 taskName
            workOrder.setStartTime(record.getCreateTime()); // createTime 映射到 startTime
            workOrder.setBusinessType(record.getBusinessType());
            workOrder.setId(record.getId());
            workOrder.setBusinessCode(record.getBusinessCode());
            workOrder.setStatus(record.getStatus());
            workOrder.setUpdateTime(record.getUpdateTime());
            workOrder.setBusinessTypeText(record.getBusinessTypeText());
            workOrderList.add(workOrder);
        }
        return workOrderList;
    }

    /**
     * @param startTime
     * @param endTime
     */
    private void getDatas(String startTime, String endTime) {

        mAccountRequester.getWorkApprovalInfoUnCompletePage(UserInfo.getInstance().getProjectCode(),
                getType() != 0,
                search,
                startTime,
                endTime, number);
    }


    public static class MessageFragmentStates extends StateHolder {

        public final State<String> time = new State<>("");
        public final State<String> timey = new State<>("");

        public final State<List<WorkOrderBean>> list = new State<>(new ArrayList<>());

        public final State<Boolean> loadingVisible = new State<>(false);

    }


    private String startTime = "";
    private String endTime = "";
    private String sources = "";

    private static SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

    public class ClickProxy {

        public void autoRefresh() {
            mBinding.smartRefreshLayout.autoRefresh();
        }

        public void screenTime() {

            startTime = "";
            endTime = "";

            boolean[] type = new boolean[]{true, true, true, false, false, false};//显示类型 默认全部显示

            TimePickerView mTimePickerView = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    startTime = ymd.format(date);

                    new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date, View v) {
                            endTime = ymd.format(date);

                            mBinding.smartRefreshLayout.autoRefresh();

                            if (0 == getType())
                                mStates.time.set(startTime + "-" + endTime);
                            else
                                mStates.timey.set(startTime + "-" + endTime);
                        }
                    }).isCyclic(false)
                            .setRangDate(null, null)
                            .setType(type)
                            .setDate(Calendar.getInstance()).build().show();


                }
            }).isCyclic(false)
                    .setRangDate(null, null)
                    .setType(type)
                    .setDate(Calendar.getInstance()).build();

            mTimePickerView.show();


        }

        public void clearTime() {

            if (0 == getType())
                mStates.time.set("");
            else
                mStates.timey.set("");

            startTime = "";
            endTime = "";

            mBinding.smartRefreshLayout.autoRefresh();
        }
    }

}
